Input : Http server input
HttpInput
is the base calss of HttpClientResponse
and HttpServerRequest
.
The client obtains the http response message through the input object. The server obtains the request information sent by the client through the input object.
HttpInput
inherits from the Readable
stream class and can easily use the pipe API to transport streams.
Support
The following shows HttpInput
module APIs available for each permissions.
User Mode | Privilege Mode | |
---|---|---|
input.url | ● | ● |
input.host | ● | ● |
input.method | ● | ● |
input.protocol | ● | ● |
input.statusCode | ● | ● |
input.headers | ● | ● |
input.header | ● | ● |
input.xhr | ● | ● |
input.body | ● | ● |
input.enableCache | ● | ● |
input.abort | ● | ● |
input.ip | ● | ● |
input.peerName | ● | ● |
input.sockName | ● | ● |
input.destroy | ● | ● |
input.pipe | ● | ● |
input.unpipe | ● | ● |
input.connected | ● | ● |
HttpOutput Object
input.url [for REQUEST]
- {String} HTTP request url.
Example
console.log(input.url);
// /index.html?name=xiaoming&age=22
input.host [for REQUEST]
- {String} HTTP request host (from header
'host'
content).
Example
// http://192.168.7.2:8080/index.html
console.log(input.host);
// 192.168.7.2:8080
input.method [for REQUEST]
- {String} Contains a string corresponding to the HTTP method of the request. It is expressed in uppercase and is case sensitive.
The method support:
DELETE, GET, HEAD, POST, PUT CONNECT, OPTIONS, TRACE COPY, LOCK, MKCOL, MOVE, PROPFIND, PROPPATCH, SEARCH, UNLOCK, BIND, REBIND, UNBIND, ACL REPORT, MKACTIVITY, CHECKOUT, MERGE MSEARCH, NOTIFY
input.statusCode [for RESPONSE]
- {Integer} HTTP response status.
Status code:
Status | Message |
---|---|
100 | Continue |
101 | Switching Protocols |
200 | OK |
201 | Created |
202 | Accepted |
203 | Non-Authoritative Information |
204 | No Content |
205 | Reset Content |
206 | Partial Content |
300 | Multiple Choices |
301 | Moved Permanently |
302 | Found |
303 | See Other |
304 | Not Modified |
305 | Use Proxy |
307 | Temporary Redirect |
400 | Bad Request |
401 | Unauthorized |
402 | Payment Required |
403 | Forbidden |
404 | Not Found |
405 | Method Not Allowed |
406 | Not Acceptable |
407 | Proxy Authentication Required |
408 | Request Timeout |
409 | Conflict |
410 | Gone |
411 | Length Required |
412 | Precondition Failed |
413 | Payload Too Large |
414 | URI Too Large |
415 | Unsupported Media Type |
416 | Range Not Satisfiable |
417 | Expectation Failed |
426 | Upgrade Required |
500 | Internal Server Error |
501 | Not Implemented |
502 | Bad Gateway |
503 | Service Unavailable |
504 | Gateway Time-out |
505 | HTTP Version Not Supported |
input.protocol [for REQUEST]
- {String} HTTP request protocol.
Example
console.log(input.protocol);
// http or https
This property is supported in EdgerOS 1.10.1 and later.
input.statusMessage [for RESPONSE]
- {String} HTTP response status message. See input.statusCode.
input.headers
- {Object} HTTP headers.
Example
console.log(input.headers.host);
// => 192.168.7.32:8000
console.log(input.headers['accept-language']);
// => zh-CN,zh;q=0.8
input.header(key)
key
{String} Header key.- Returns: {String} Header value.
Example
console.log(input.getHeader('Host'));
input.xhr [for REQUEST]
- {Boolean} If HTTP header
X-Requested-With
exist.
A Boolean property that is true
if the request’s X-Requested-With
header field is XMLHttpRequest
, indicating that the request was issued by a client library such as jQuery.
Example
console.log(input.xhr);
// => true
input.body
- {Object | Buffer | String} Request body, default: {}.
If enableCache()
is set, input data will be stored in input.body
in Buffer
type. If enableCache()
is not set or input data is empty, then input.body
remains {}
. See input.enableCache().
input.enableCache(cache)
cache
{Boolean} Enable cache or not, default: true.
If enableCache(true)
is set, the input data will be stored in input.body
in Buffer
type when input receives data.
enableCache(false)
meens empty the cache.
Example
- Collect data from
data
events
var http = require('http');
http.request('http://192.168.7.32:8000/get', function(res) {
var data = [];
res.on('data', (buf) => {
data.push(buf);
});
res.on('end', () => {
data = Buffer.concat(data);
var str = data.toString();
console.log(`receive body: ${str}`);
});
});
- Cache data to
body
:
var http = require('http');
http.request('http://192.168.7.32:8000/get', function(res) {
res.enableCache();
res.on('end', () => {
console.log('get recv data:', res.body.toString());
});
});
input.abort()
If the data reception is not completed or is not aborted, the input data is aborted. The ‘aborted` event is fired when this operation is active.
In REQUEST mode, if the user replies to the request(write, end ... operator) before the data is received, the receiving process will automatically abort and the 'aborted' event will fire.
Example
var HttpServer = require('http_server');
var socket = require('socket');
var server = HttpServer.createServer('http', handle, 0, socket.sockaddr(socket.INADDR_ANY, 8000));
function handle(req, res) {
var data = [];
var len = 0;
req.on('data', (buf) => {
len += buf.length;
if (len > 1024 * 4) {
req.abort();
} else {
data.push(buf);
}
});
req.on('end', () => {
data = Buffer.concat(data);
var str = data.toString();
res.end(`receive body: ${str}`);
});
req.on('aborted', () => {
console.log(`the body is too big`);
res.status(400);
res.end();
});
}
input.ip
- {String}
Get the IP address of the remote client.
input.peerName()
- Returns: {Object} Returns remote client address.
Get the address of the remote client, includes following items:
domain
{Integer} Address domain:socket.AF_INET
orsocket.AF_INET6
.addr
{String} Address.port
{Integer} Port.
input.sockName()
- Returns: {Object} Returns my connect address.
Get the address of the my connect.
input.destroy([error])
error
{Error} which will be passed as payload in'error'
event.- Returns: {HttpInput} This object.
When this method closes the readable
stream, it also closes the underlying socket connection.
input.pipe(destination[, options])
destination
{Writable} The destination for writing data.options
{Object} Pipe options:end
{Boolean} End the writer when the reader ends. default:true
.
- Returns: {Writable} The destination, allowing for a chain of pipes if it is a
Duplex
stream.
Pipe data from input
to writable
stream object. More to see readable.pipe.
Example
var HttpServer = require('http_server');
var socket = require('socket');
var iosched = require('iosched');
var WriteStream = require('stream/fs_writestream');
HttpServer.createServer('http', handle, 0, socket.sockaddr(socket.INADDR_ANY, 8000));
function handle(req, res) {
var wStream = WriteStream.createWriteStream('./tem.tem');
var finished = false;
wStream.on('error', (err) => {
console.error('on write stream error:', err);
if (finished) {
return;
}
finished = true;
res.sendStatus(500, err.message);
});
req.on('error', (err) => {
console.error('on req error:', err);
if (finished) {
return;
}
finished = true;
wStream.destroy();
res.sendStatus(500, err.message);
});
req.on('end', () => {
if (finished) {
return;
}
finished = true;
res.send('ok');
})
req.pipe(wStream);
}
iosched.forever();
input.unpipe([destination])
destination
{Writable} Optional specific stream to unpipe.- Returns:{HttpInput} This object.
The input.unpipe()
method detaches a Writable
stream previously attached using the stream.pipe()
method. More to see readable.unpipe.
input.connected()
- Returns: {Boolean} Whether the current connection is connected.
Get whether the current network connection is connected.
Example
var connected = input.connected();